package com.wl.cloud.core.mybatis;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.wl.cloud.core.constants.ColumnsConstants;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.security.core.context.SecurityContextHolder;

import java.time.LocalDateTime;

/**
 * @author: wanglin
 * @date: 2023-12-18 周一
 * @Version: 1.0
 * @Description: Mybatis-plus自动填充创建时间、创建人、修改时间、修改人字段
 */
public class CustomMetaObjectHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        setInsertFieldValByName(ColumnsConstants.SYS_CREATE_TIME, LocalDateTime.now(), metaObject);
        setInsertFieldValByName(ColumnsConstants.SYS_UPDATE_TIME, LocalDateTime.now(), metaObject);
        String username = (String) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        setInsertFieldValByName(ColumnsConstants.SYS_CREATE_BY, username, metaObject);
        setInsertFieldValByName(ColumnsConstants.SYS_UPDATE_BY, username, metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        setUpdateFieldValByName(ColumnsConstants.SYS_UPDATE_TIME, LocalDateTime.now(), metaObject);
        String username = (String) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        setUpdateFieldValByName(ColumnsConstants.SYS_UPDATE_BY, username, metaObject);
    }
}
